#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <set>
#include "tree.h"

using namespace std;

void printKth(Tree *root, int& k)
{
    if (!root) return;
    printKth(root->left, k);
    k--;
    if (k == 0) cout << root->data << endl;
    printKth(root->right, k);    
}

void printKthIterative(Tree *root, int k)
{
    stack<Tree *> stk;
    Tree *cur = root;
    while(cur || !stk.empty()) {
        if (cur ) {
	    stk.push(cur);
	    cur = cur->left;
	} else {
	    Tree *top = stk.top();
	    stk.pop();
	    k--;
	    if (k == 0) cout << top->data << endl;
	    cur = top->right; 
	}
    }
}

int main(int argc, char **argv)
{
    int input[] = {21,7,5,6,3,2,1,4,6,23,43,54,12,54,8,10,11,35,56};
    //int input[] = {7};
    Tree *root = NULL, *root2 = NULL;
    int result;

    for (int i = 0; i < sizeof(input)/sizeof(int); i++) {
        TreeInsert(root, input[i]);
    }

    print_ascii_tree(root);

    for (int i = 1; i < 5; i++)   {
        int k = i;
	printKthIterative(root, k);
    }

}
